package com.yanqu.road.server.gameplayer.module.activity.jianchuanghua;

import com.yanqu.road.entity.activity.jianchuanghua.ChuangHuaComb;
import com.yanqu.road.entity.activity.jianchuanghua.ChuangHuaInfo;
import com.yanqu.road.entity.activity.jianchuanghua.ChuangHuaUserData;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.logic.bussiness.activity.JianChuangHuaBussiness;
import com.yanqu.road.pb.activity.JianChuangHuaProto;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.manger.ServerLanguageMgr;
import com.yanqu.road.server.manger.activity.jianchuanghua.JianChuangHuaMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class JianChuangHuaModule extends GeneralModule {

    private ChuangHuaUserData userData;

    private Random random = new Random();

    public JianChuangHuaModule(GamePlayer player) {
        super(player);
    }

    @Override
    public boolean loadData() {
        if (SystemOpenMgr.systemOpen(player, eSystemId.JianChuangHuaActivity.getValue())) {
            int showTimeActivityId = JianChuangHuaMgr.getShowTimeActivityId();
            if (showTimeActivityId != 0) {
                userData = JianChuangHuaBussiness.getChuangHuaUserData(player.getUserId(), showTimeActivityId);
                if (userData == null) {
                    initUserData();
                }
            }
        }
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return true;
    }

    @Override
    public void afterLogin() {
        if (userData != null) {
            syncJianChuangHuaConfig();
            syncChuangHuaCount();
        }
    }

    @Override
    public boolean saveData() {
        if (userData == null) {
            return true;
        }
        if (userData.isInsertOption()) {
            JianChuangHuaBussiness.addChuangHuaUserData(userData);
        } else if (userData.isUpdateOption()) {
            JianChuangHuaBussiness.updateChuangHuaUserData(userData);
        }
        return true;
    }

    /**
     * 减少剪刀（数量不够返回false）
     */
    public boolean reduceScissors(int count) {
        if (userData == null) {
            return false;
        }
        Property property = new Property();
        property.addProperty(JianChuangHuaMgr.scissorsItemId, BigInteger.valueOf(count));
        CurrencyModule currencyModule = player.getModule(CurrencyModule.class);
        if (currencyModule.currencyIsEnough(property)) {
            currencyModule.removeCurrency(property, eLogMoneyType.JianChuangHua, eLogMoneyType.JianChuangHuaCutConsume);
            return true;
        }
        return false;
    }

    /**
     * 剪一剪
     * return 窗花ID List
     */
    public List<Integer> cutByTimes(int times) {
        if (userData == null) {
            return new ArrayList<>();
        }
        List<Integer> result = new ArrayList<>();
        Property chuangHuaProp = new Property();
        int addScore = 0;

        // 抽
        List<ChuangHuaInfo> chuangHuaInfoList = JianChuangHuaMgr.getRandomChuangHuaInfoList(times, random);
        for (ChuangHuaInfo chuangHuaInfo : chuangHuaInfoList) {
            result.add(chuangHuaInfo.getId());
            addScore += chuangHuaInfo.getIntegral();
            chuangHuaProp.addProperty(chuangHuaInfo.getId(), BigInteger.ONE);
        }

        // 加积分到背包
        Property scoreProp = new Property();
        scoreProp.addProperty(JianChuangHuaMgr.scoreItemId, BigInteger.valueOf(addScore));
        player.getModule(CurrencyModule.class).addCurrency(scoreProp, eLogMoneyType.JianChuangHua, eLogMoneyType.JianChuangHuaCutGet);

        // 加积分到榜单
        userData.setScore(userData.getScore() + addScore);
        player.notifyListener(eGamePlayerEventType.JianChuangHuaScoreRank.getValue(), userData.getScore());
        player.notifyListener(eGamePlayerEventType.JianChuangHuaScoreCrossRank.getValue(), userData.getScore());

        // 加窗花
        userData.getChuangHuaProperty().addProperty(chuangHuaProp);
        userData.setUpdateOption();

        // 检查组合
        updateChuangHuaCombTimes();

        syncChuangHuaCount();

        // 返回结果
        return result;
    }

    /**
     * 同步窗花数量
     */
    public void syncChuangHuaCount() {
        if (userData == null) {
            return;
        }
        JianChuangHuaProto.SyncChuangHuaDataRespMsg.Builder builder = JianChuangHuaProto.SyncChuangHuaDataRespMsg.newBuilder();
        builder.setChuangHuaList(PropertyHelper.parsePropertyToString(userData.getChuangHuaProperty()));
        player.sendPacket(ClientProtocol.U_ACTIVITY_JIAN_CHUANG_HUA_COUNT_SYNC, builder);
    }

    /**
     * 检查窗花组合达成
     */
    public void updateChuangHuaCombTimes() {
        if (userData == null) {
            return;
        }
        JianChuangHuaMgr.updateChuangHuaCombTimes(player, userData.getChuangHuaProperty());
    }

    /**
     * 初始化用户数据
     */
    public synchronized void initUserData() {
        int showTimeActivityId = JianChuangHuaMgr.getShowTimeActivityId();
        if (userData != null && userData.getActivityId() == showTimeActivityId) {
            return;
        }
        ChuangHuaUserData tmpUserData = new ChuangHuaUserData();
        tmpUserData.setUserId(player.getUserId());
        tmpUserData.setActivityId(showTimeActivityId);
        tmpUserData.setScore(0);
        tmpUserData.setChuangHuaProperty(new Property());
        tmpUserData.setInsertOption();
        userData = tmpUserData;
    }

    /**
     * 初始化系统
     */
    public void initSystem() {
        int inTimeActivityId = JianChuangHuaMgr.getShowTimeActivityId();
        if (inTimeActivityId == 0) {
            userData = null;
            return; // 没有活动
        }
        userData = JianChuangHuaBussiness.getChuangHuaUserData(player.getUserId(), inTimeActivityId);
        if (userData == null) {
            initUserData();
        }
        syncJianChuangHuaConfig();
        syncChuangHuaCount();
    }

    /**
     * 同步剪窗花配置数据
     */
    public void syncJianChuangHuaConfig() {
        if (!JianChuangHuaMgr.isActivityInShowTime()) {
            return;
        }

        JianChuangHuaProto.SyncJianChuangHuaConfigRespMsg.Builder builder = JianChuangHuaProto.SyncJianChuangHuaConfigRespMsg.newBuilder();
        // 窗花
        List<JianChuangHuaProto.ChuangHuaMsg> infoMsgList = new ArrayList<>();
        List<ChuangHuaInfo> infoList = JianChuangHuaMgr.getChuangHuaInfoList();
        for (ChuangHuaInfo info : infoList) {
            JianChuangHuaProto.ChuangHuaMsg.Builder tmpBuilder = JianChuangHuaProto.ChuangHuaMsg.newBuilder();
            tmpBuilder.setDesc(ServerLanguageMgr.getContent(info.getDesc(), player.getLanguage()));
            tmpBuilder.setName(ServerLanguageMgr.getContent(info.getName(), player.getLanguage()));
            tmpBuilder.setChuangHuaId(info.getId());
            tmpBuilder.setIntegral(info.getIntegral());
            tmpBuilder.setQuality(info.getQuality());
            tmpBuilder.setWeight(info.getWeight());
            tmpBuilder.setSort(info.getSort());
            infoMsgList.add(tmpBuilder.build());
        }
        // 窗花组合
        List<JianChuangHuaProto.ChuangHuaCombMsg> combMsgList = new ArrayList<>();
        List<ChuangHuaComb> combList = JianChuangHuaMgr.getChuangHuaCombList();
        for (ChuangHuaComb comb : combList) {
            JianChuangHuaProto.ChuangHuaCombMsg.Builder tmpBuilder = JianChuangHuaProto.ChuangHuaCombMsg.newBuilder();
            tmpBuilder.setDesc(ServerLanguageMgr.getContent(comb.getDesc(), player.getLanguage()));
            tmpBuilder.setElements(comb.getElement());
            tmpBuilder.setName(ServerLanguageMgr.getContent(comb.getName(), player.getLanguage()));
            tmpBuilder.setCombId(comb.getCombId());
            tmpBuilder.setQuality(comb.getQuality());
            tmpBuilder.setSort(comb.getSort());
            combMsgList.add(tmpBuilder.build());
        }
        // 组装结果
        builder.addAllChuangHuaList(infoMsgList);
        builder.addAllChungHuaCombList(combMsgList);
        player.sendPacket(ClientProtocol.U_ACTIVITY_JIAN_CHUANG_HUA_CONFIG_SYNC, builder);
    }

    public ChuangHuaUserData getUserData() {
        return userData;
    }
}
